//
//  XAIGateway.m
//  YSSmartHome
//
//  Created by Yahaong on 16/8/25.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "XAIGateway.h"
#import "MQTTCoverTool.h"
#import "MQTTSessionManager.h"
#import "DataManager.h"
#import "ZTDeviceUtil.h"
#import "ZTLinkageUtil.h"
#import "JPUSHService.h"
#import "Find2DevView.h"
#import "GlobalConst.h"
#import "YHProgressHUD.h"

@interface XAIGateway ()
@property(nonatomic,assign)XAITYPEAPSN bindingApsn;
@property (nullable, nonatomic, strong) MQTTSessionManager* sessionManager;
@property (nullable, nonatomic, strong) DataManager* dataManager;
@end
@implementation XAIGateway

- (instancetype)initWithApsn:(XAITYPEAPSN)apsn Luid:(XAITYPELUID)luid type:(ZTDeviceType)type {
    self = [super initWithApsn:apsn Luid:luid type:type];
    if (self) {
        self.name = @"宇数智能家居";
    }
    return self;
}
- (void)getGatewayStatus{
    NSString* topicStr = [MQTTCoverTool gatewayAllStatusTableTopicWithAPNS:self.apsn];
//    [kMQTTSessionManager.mqttClient subscribe:topicStr withQos:ExactlyOnce];
    

}
- (void)unsubscribeGatewayStatus{
    NSString* topicStr = [MQTTCoverTool gatewayAllStatusTableTopicWithAPNS:self.apsn];
//    [kMQTTSessionManager.mqttClient unsubscribe:topicStr];
}

- (void)bindingExtraInfo:(NSString * __nullable)info
{
    XAITYPEAPSN apsn = self.apsn;
    XAIFormatDataCount *formatCount = [[XAIFormatDataCount alloc] init];
    [formatCount addDataType:XAI_DATA_TYPE_BIN_APSN bytes:&apsn length:sizeof(apsn)];
    [formatCount addDataType:XAI_DATA_TYPE_ASCII_TEXT bytes:(void*)[info UTF8String] length:(int)[info dataUsingEncoding:NSUTF8StringEncoding].length];
    [kMQTTSessionManager sendCmd:0x01 toApsn:self.apsn toLuid:self.luid data:formatCount];
}
- (void)binding:(XAITYPEAPSN)apsn extraInfo:(NSString * __nullable)info
{
   
    XAIFormatDataCount *formatCount = [[XAIFormatDataCount alloc] init];
    [formatCount addDataType:XAI_DATA_TYPE_BIN_APSN bytes:&apsn length:sizeof(apsn)];
    [formatCount addDataType:XAI_DATA_TYPE_ASCII_TEXT bytes:(void*)[info UTF8String] length:(int)[info dataUsingEncoding:NSUTF8StringEncoding].length];
    [kMQTTSessionManager sendCmd:0x01 toApsn:self.apsn toLuid:self.luid data:formatCount];
}

- (void)bindSharedGateway: (XAITYPEAPSN )apsn num :(uint32_t)num
{
    self.bindingApsn = apsn;
    XAIFormatDataCount *formatDataCount = [[XAIFormatDataCount alloc] init];
    [formatDataCount addDataType:XAI_DATA_TYPE_BIN_APSN bytes:&apsn length:sizeof(XAITYPEAPSN)];
    [formatDataCount addDataType:XAI_DATA_TYPE_BIN_DIGITAL_UNSIGN bytes:&num length:sizeof(num)];
    [kMQTTSessionManager sendCmd:0x07 toApsn:kZTCloudGatewayApsn toLuid:kGATEWAYLUID data:formatDataCount];
    
}

- (void)unbind
{
    XAITYPEAPSN apsn = self.apsn;
    XAITYPELUID luid = self.luid;
    XAITLV* apsnTLV = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_APSN bytes:&apsn length:sizeof(apsn)];
    XAITLV* luidTLV = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_LUID bytes:&luid length:sizeof(luid)];
    NSError* error = [kMQTTSessionManager.xai sendCMD:0x02 toApsn:kZTCloudGatewayApsn toLuid:kGATEWAYLUID datas:@[apsnTLV,luidTLV]];
    NSLog(@"%@",error.localizedDescription);
    
}
- (void)sendShredInfo:(uint32_t)num
{
    XAITYPEAPSN apsn = kMQTTSessionManager.currentGateway.apsn;
    NSMutableArray* array = [NSMutableArray array];
    XAITLV* tlv = [[XAITLV alloc]init];
    tlv.type = XAI_DATA_TYPE_BIN_APSN;
    [tlv setPayloadbyte:&apsn  withSize:sizeof(apsn)];
    [array addObject:tlv];
    tlv = [[XAITLV alloc]init];
    tlv.type = XAI_DATA_TYPE_BIN_DIGITAL_UNSIGN;
    [tlv setPayloadbyte:&num  withSize:sizeof(num)];
    [array addObject:tlv];
    
    NSError* error =  [kMQTTSessionManager.xai sendCMD:0x06 toApsn:kZTCloudGatewayApsn toLuid:kGATEWAYLUID datas:array];
    if (error.code == 0) {
        debugLogInfo(@"网关分享成功");
    }
    else
    {
        debugLogInfo(@"网关分享失败");
    }
    
}
- (void)modifyGateName:(NSString * __nullable)name
{
    XAIFormatDataCount* formatCount = [[XAIFormatDataCount alloc]init];
    XAITYPEAPSN devApsn = self.apsn;
    [formatCount addDataType:XAI_DATA_TYPE_BIN_APSN bytes:&devApsn length:sizeof(devApsn)];
    
    XAITYPELUID devLuid = self.luid;
    [formatCount addDataType:XAI_DATA_TYPE_BIN_LUID bytes:&devLuid length:sizeof(devLuid)];
    uint8_t status = 0xff;
    [formatCount addDataType:XAI_DATA_TYPE_BIN_DIGITAL_UNSIGN bytes:&status length:sizeof(status)];
    [formatCount addDataType:XAI_DATA_TYPE_ASCII_TEXT bytes:(void*)[name cStringUsingEncoding:NSUTF8StringEncoding] length: (int)[name dataUsingEncoding:NSUTF8StringEncoding].length];
    [kMQTTSessionManager sendCmd:0x09 toApsn:self.apsn toLuid:self.luid data:formatCount];
}

- (void)reciveACK:(XAIPKTAck *)pktAck
{
    if (pktAck == nil) return;
    if (pktAck.scid == 0x01)
    {
        if (pktAck.error != 0)
        {
            debugLogInfo(@"设备删除出现了错误啊");
            self.bindingApsn = 0;
            [YHProgressHUD showErrorWithStatus:@"设备删除出错"];
            return;
        }
        debugLogInfo(@"设备删除命令成功");
    }
    else if (pktAck.scid == 0x07)
    {
        if (pktAck.error != 0)
        {
            debugLogInfo(@"添加设备出错%zd",pktAck.error);
            return;
        }
        debugLogInfo(@"添加设备成功");
    }
    else if (pktAck.scid == 0x09)
    {
        if (pktAck.error != 0)
        {
            debugLogInfo(@"node设备属性修改出错");
            return;
        }
        debugLogInfo(@"node设备属性修改成功");
    }
}

- (void)reciveStatus:(uint32_t)gatewayApsn
          deviceLuid:(uint64_t )deviceLuid
         triggerApsn:( uint32_t)triggerApsn
         triggerLuid:(uint64_t)triggerLuid
           timestamp:(uint32_t)timestamp
            statusID:(uint8_t)statusID
                data:(XAITLV*__nonnull)data
           isHistory:(BOOL)isHistory {
    if (!data) {
        return;
    }
    switch (statusID) {
        case 0xff:
        {
            self.name = [[NSString alloc]initWithBytes:[data getPayloadbyte] length:data.payloadlen encoding:NSUTF8StringEncoding];
            debugLogInfo(@"网关名字 = %@",self.name);
            [self.dataManager gatewayCallBackWithType:GatewayCallbackTypeName];
        }
            break;
        case 0xfe:
        {   uint8_t status = 0;
            memcpy(&status, [data getPayloadbyte], sizeof(uint8_t));
            self.devStatus  = status;
            if (self.apsn == self.sessionManager.currentUser.currentBindApsn) {
                [kDataManager callBack];
            }
            [kDataManager gatewayCallBackWithType:GatewayCallbackTypeConnectStatus];
        }
            break;
        case 0xfd:
        {   uint8_t status = 0;
            memcpy(&status, [data getPayloadbyte], sizeof(uint8_t));
            [kDataManager gatewayCallBackWithType:GatewayCallbackTypePower];
        }
            break;
        case 0x01:
        {
            uint8_t linkID = 0;
            memcpy(&linkID, [data getPayloadbyte], sizeof(uint8_t));
            self.linkID = linkID;
            debugLogInfo(@"%08x当前的场景是%zd",self.apsn,linkID);
            [kDataManager gatewayCallBackWithType:GatewayCallbackTypeLinkage];
        }
            break;
        case 0x02:
        {
            uint64_t newdevLuid = 0;
            memcpy(&newdevLuid, [data getPayloadbyte], sizeof(newdevLuid));
            newdevLuid = CFSwapInt64(newdevLuid);
            debugLogInfo(@"%08x收到新设备%016llx",self.apsn,newdevLuid);
            [kDataManager setUnJoinDevList:@(newdevLuid)];
        }
            break;
        default:
            break;
    }
}

#pragma mark - getters and setters 

- (MQTTSessionManager *)sessionManager {
    if (!_sessionManager) {
        _sessionManager = [MQTTSessionManager sharedManager];
    }
    return _sessionManager;
}

- (DataManager *)dataManager {
    if (!_dataManager) {
        _dataManager = [DataManager sharedManager];
    }
    return _dataManager;
}
@end
